package com.ruoyi.common.core.utils;

import com.ruoyi.common.core.exception.BaseException;
import com.ruoyi.common.core.utils.bean.BeanUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author liyang
 * @apiNote entity转dto工具类
 * @date 2021/6/9 10:28
 */
public class ConvertUtil {

    public ConvertUtil() {
        throw new BaseException("反射异常");
    }

    /**
     * 将单个类转换成另外一种类
     *
     * @param source
     * @param target
     * @param <T>
     * @return
     */
    public static <T> T sourceToTarget(Object source, Class<T> target) {
        if (source == null) {
            return null;
        }
        T targetObject = null;
        try {
            targetObject = target.newInstance();
            BeanUtils.copyProperties(source, targetObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return targetObject;
    }

    /**
     * 将多个类转换成另外一种类
     *
     * @param sourceList
     * @param target
     * @param <T>
     * @return
     */
    public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target) {
        if (sourceList == null) {
            return null;
        }
        List<T> targetList = new ArrayList<>(sourceList.size());
        try {
            for (Object source : sourceList) {
                T targetObject = target.newInstance();
                BeanUtils.copyProperties(source, targetObject);
                targetList.add(targetObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return targetList;
    }

}
